//
//  YSReviewsHeaderView.m
//  Yueshi
//
//  Created by Northwan on 15/8/14.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSReviewsHeaderView.h"
#import "YSProductListGridItemCell.h"
#import "YSProductDetailCtrl.h"
#import "YSReviewsCtrl.h"
#import "YSReviewsComtHeaderView.h"
#import "YSVirtualProtocol.h"
#import "YSHomeDataTool.h"

#define TITLE_FONT_SIZE 18
#define PRAISE_FONT_SIZE 18

@interface YSReviewsHeaderView()<UIWebViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,YSReviewsComtHeaderViewDelegate>
@property (nonatomic, strong) UILabel *styleLabel;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIButton *praiseBtn;
@property (nonatomic, strong) UILabel *fromLabel;
@property (nonatomic, strong) UICollectionView *collectView;
@property (nonatomic, strong) NSArray *prodArray;
@property (nonatomic, strong) YSReviews *reviews;
@property (nonatomic, strong) UILabel  *likeLabel;
@property (nonatomic, strong) UILabel  *markTipLabel;
@property (nonatomic, strong) YSReviewsComtHeaderView  *commentHeaderView;

@property (nonatomic, assign) BOOL havaData;

@end

@implementation YSReviewsHeaderView


-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self!=nil){
        [self setBackgroundColor:PUBLIC_CARD_BG];
        
        UIView *titleLineLeftView = [[UIView alloc]initWithFrame:CGRectMake(YSPublicXInset, YSPublicXInset, 2, YSPublicXInset*2)];
        [titleLineLeftView setBackgroundColor:ThemeColor];
        [self addSubview:titleLineLeftView];
        
        //TODO: - 添加一个标签头
        
        //添加标题
        _titleLabel  = [UILabel new];
        [_titleLabel setBackgroundColor:PUBLIC_CARD_BG];
        [_titleLabel setNumberOfLines:0];
        [_titleLabel setFont:SYS_FONT(TITLE_FONT_SIZE)];
        _titleLabel.x = CGRectGetMaxX(titleLineLeftView.frame)+YSPublicXInset;
        _titleLabel.y = YSPublicXInset;
        [_titleLabel setTextColor:HEXColor(@"#333333")];
        [self addSubview:_titleLabel];
        
        //添加来源
        _fromLabel = [[UILabel alloc]init];
        [_fromLabel setFont:[UIFont systemFontOfSize:13]];
        [_fromLabel setTextColor:HEXColor(@"#9E9E9E")];
        [_fromLabel setX:0];
        [_fromLabel setY:CGRectGetMaxY(_titleLabel.frame)+YSPublicXInset];
        [self addSubview:_fromLabel];
        
        //添加webview
        _webView = [[UIWebView alloc]init];
        [_webView setDelegate:self];
        [_webView setX:0];
        [_webView.scrollView setScrollEnabled:NO];
        [_webView setY:CGRectGetMaxY(_fromLabel.frame) + YSPublicXInset];
        [_webView setWidth:SCREENW];
        [_webView setHeight:SCREENH];
        [self addSubview:_webView];
        [self addKVO];
        
        //添加点赞
        _praiseBtn = [[UIButton alloc]init];
        [_praiseBtn addTarget:self action:@selector(praiseReviews) forControlEvents:UIControlEventTouchUpInside];
        UIImage * unPraiseImage = [UIImage imageNamed:@"btn_mark_reviews_normal"];
        [_praiseBtn setImage:unPraiseImage forState:UIControlStateNormal];
        UIImage * praiseImage = [UIImage imageNamed:@"btn_mark_reviews_press"];
        [_praiseBtn setImage:praiseImage forState:UIControlStateSelected];
        [_praiseBtn setImage:praiseImage forState:UIControlStateDisabled];
        
        [_praiseBtn.titleLabel setFont:[UIFont systemFontOfSize:PRAISE_FONT_SIZE]];
        [_praiseBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        [_praiseBtn setTitleColor:ThemeColor forState:UIControlStateDisabled];
        
        [_praiseBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
        [_praiseBtn setTitle:@"0" forState:UIControlStateNormal];
        [_praiseBtn setFrame:CGRectMake((SCREENW-90)/2, CGRectGetMaxY(_webView.frame)+YSPublicXInset,90,30)];
        [self addSubview:_praiseBtn];
        [_praiseBtn setBackgroundColor:[UIColor whiteColor]];
        [_praiseBtn setCornerRadius:5 borderWidth:0.5 borderColor:RGBColor(234, 234, 233)];
        
        //提示收藏的label
        UILabel *markTipLabel = [[UILabel alloc]init];
        [markTipLabel setText:@"收藏"];
        [markTipLabel setFont:SYS_FONT(18)];
        CGSize markTipLabelSize = [markTipLabel.text sizeWithFont:SYS_FONT(18)];
        [markTipLabel setFrame:CGRectMake(CGRectGetMinX(_praiseBtn.frame)-markTipLabelSize.width-YSPublicXInset, CGRectGetMinY(_praiseBtn.frame), markTipLabelSize.width, markTipLabelSize.height)];
        [self addSubview:markTipLabel];
        _markTipLabel = markTipLabel;
        
        //猜你喜欢
        _likeLabel = [UILabel new];
        NSString *likePlaceholder = @"猜你喜欢";
        [_likeLabel setHidden:YES];
        CGSize likePlaceHolderSize =  [likePlaceholder sizeWithFont:SYS_FONT(TITLE_FONT_SIZE)];
        [_likeLabel setFont:SYS_FONT(TITLE_FONT_SIZE)];
        [_likeLabel setText:likePlaceholder];
        [_likeLabel setFrame:CGRectMake((SCREENW-likePlaceHolderSize.width)/2, CGRectGetMaxY(_praiseBtn.frame)+YSPublicXInset, likePlaceHolderSize.width, TITLE_FONT_SIZE)];
        [self addSubview:_likeLabel];
        
        //collectionview
        UICollectionViewFlowLayout *flowLayout =[[UICollectionViewFlowLayout alloc]init];
        UICollectionView *collectView  =[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
        collectView.backgroundColor = PUBLIC_CARD_BG;
        [collectView registerClass:[YSProductListGridItemCell class] forCellWithReuseIdentifier:@"YSProductListGridItemCell"];
        _collectView = collectView;
        [self addSubview:collectView];
        
        _commentHeaderView = [YSReviewsComtHeaderView comtHeaderView];
        [_commentHeaderView setHidden:YES];
        [_commentHeaderView setWidth:SCREENW];
        [_commentHeaderView setX:0];
        [_commentHeaderView setY:CGRectGetMaxY(collectView.frame)];
        [_commentHeaderView setDelegate:self];
        [self addSubview:_commentHeaderView];
    }
    return self;
}

/**
 *  添加webview的内容改变监听
 */
-(void)addKVO{
    UIScrollView *scrollview = [[_webView subviews]firstObject];
    [scrollview addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if([keyPath isEqualToString:@"contentSize"])
    {
        NSValue *oldSize = [change objectForKey:@"old"];
        NSValue *newSize = [change objectForKey:@"new"];
        if ([oldSize CGSizeValue].height!=[newSize CGSizeValue].height) {
            [self webViewDidFinishLoad:_webView];
        }
    }
}

-(void)openComment{
    if([_delegate respondsToSelector:@selector(openComment)]){
        [_delegate openComment];
    }
}

-(void)setTitle:(NSString *)title{
    [_titleLabel setText:title];
    CGSize titleSize = [title sizeWithFont:SYS_FONT(TITLE_FONT_SIZE) constrainedToSize:CGSizeMake(SCREENW-YSPublicXInset*2, MAXFLOAT)];
    [_titleLabel setSize:titleSize];
}

- (void)setReviewsData:(YSReviews *)reviews prodList:(NSArray *)prodList{
    _havaData = YES;
    _reviews = reviews;
    _prodArray = [NSMutableArray arrayWithArray:prodList];
    
    if (reviews.reviewsType == YSReviewsVipType){//增加一个标签
        
    }
    
    [_titleLabel setText:reviews.postName];
    CGSize titleSize = [reviews.postName sizeWithFont:SYS_FONT(TITLE_FONT_SIZE) constrainedToSize:CGSizeMake(SCREENW-YSPublicXInset*2, MAXFLOAT)];
    [_titleLabel setSize:titleSize];
    NSString *from =  [NSString stringWithFormat:@"%@%@",reviews.createTime,reviews.resource];
    [_fromLabel setText:from];
    CGSize fromSize =  [from sizeWithFont:[UIFont systemFontOfSize:PRAISE_FONT_SIZE]];
    [_fromLabel setSize:fromSize];
    [_fromLabel setFrame:CGRectMake(CGRectGetMinX(_titleLabel.frame), CGRectGetMaxY(_titleLabel.frame)+YSPublicXInset, fromSize.width, fromSize.height)];
    [_webView loadHTMLString:reviews.content baseURL:nil];
    [_webView setY:CGRectGetMaxY(_fromLabel.frame)+YSPublicXInset];
    
    NSString *praiseNum = [NSString stringWithFormat:@"%ld",reviews.praiseNum];
    [_praiseBtn setTitle:praiseNum forState:UIControlStateNormal];
    [_praiseBtn setSelected:reviews.isPraise];
}

-(void)praiseReviews{
    if(ISLOGIN){
        NSInteger type =  _praiseBtn.isSelected?ResultFailureType:ResultSuccessType;
        [YSHomeDataTool markReviewsWithReviewsId:[NSString stringWithFormat:@"%ld",_reviews.id]type:type success:^(BaseResponse *result) {
            if(result.isSucc){
                if(type == ResultSuccessType){
                    [self.praiseBtn setSelected:YES];
                    UIView* view = self.praiseBtn.imageView;
                    view.transform = CGAffineTransformMakeScale(2.0, 2.0);
                    [UIView animateWithDuration:1 delay:0 usingSpringWithDamping:0.2 initialSpringVelocity:0 options:UIViewAnimationOptionLayoutSubviews animations:^{
                        view.transform = CGAffineTransformIdentity;
                    } completion:^(BOOL finished) {
                        NSInteger count = _praiseBtn.titleLabel.text.integerValue+1;
                        NSString *value = [NSString stringWithFormat:@"%ld",count];
                        [self.praiseBtn setTitle:value forState:UIControlStateNormal];
                        ShowTips(@"收藏成功");
                    }];
                }else{
                    [self.praiseBtn setSelected:NO];
                    NSInteger count = _praiseBtn.titleLabel.text.integerValue-1;
                    NSString *value = [NSString stringWithFormat:@"%ld",count];
                    [self.praiseBtn setTitle:value forState:UIControlStateNormal];
                    ShowTips(@"已取消收藏")
                }
            }else{
                ShowEnterTips(result.data)
            }
        } failure:^(NSError *error) {
            ShowTips(kRequestFailure)
        }];
    }else{
        [Utils showLoginCtrl:self.viewController];
    }
}

- (NSString *)decodeFromPercentEscapeString: (NSString *) input
{
    NSMutableString *outputStr = [NSMutableString stringWithString:input];
    [outputStr replaceOccurrencesOfString:@"+"
                               withString:@" "
                                  options:NSLiteralSearch
                                    range:NSMakeRange(0, [outputStr length])];
    
    return [outputStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

-(void)webViewDidStartLoad:(UIWebView *)webView{
    
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
}

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *url = [self decodeFromPercentEscapeString:[request.URL absoluteString]];

    NSLog(@"伪链接url=%@",url);
    NSString *prefixStr  = @"yueshiopen://virtual?params=";
    if([url hasPrefix:prefixStr]){
        NSRange range =  [url rangeOfString:prefixStr];
        NSString  *newUrl = [url substringFromIndex:range.length];
        NSDictionary *params = [Utils dictionaryWithJsonString:newUrl];
        YSVirtualProtocol *protocol = [YSVirtualProtocol objectWithKeyValues:params];
        if(protocol.linkType == YSVirtualProtocolAddCartProdMode){//加入购物篮
            if([_delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]){
                [_delegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
            }
            return NO;
        }else if(protocol.linkType == YSVirtualProtocolBuyProdMode){//立即购买
            if([_delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]){
                [_delegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
            }
            return NO;
        }
    }
    
    if ([Utils dealUrlWithController:self.viewController url:url fromWebView:YES]) {
        NSString *suffix = @"login=1";
        if ([url hasSuffix:suffix]) {
            NSString *token = [DefaultsHelper stringForKey:kAppToken];
            url = [url stringByAppendingFormat:@"&token=%@", token];
            
            [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
            return NO;
        }
    }
    return YES;
}


-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
    CGSize actualSize = [webView sizeThatFits:CGSizeZero];
    _webView.scrollView.contentSize = actualSize;
    [webView setHeight:actualSize.height];
    
    _praiseBtn.y = CGRectGetMaxY(webView.frame)+YSPublicXInset*2;
    _markTipLabel.y =  _praiseBtn.y+5;
    
    [_commentHeaderView setHidden:NO];
    _commentHeaderView.y = CGRectGetMaxY(_praiseBtn.frame)+YSPublicXInset;
    
    self.frame = CGRectMake(0, 0, SCREENW, CGRectGetMaxY(_commentHeaderView.frame));
    
    if(_prodArray!=nil &&_prodArray.count>0){
        _collectView.delegate = self;
        _collectView.dataSource=self;
        
        CGFloat likeViewY = CGRectGetMaxY(_praiseBtn.frame)+YSPublicXInset;
        [_likeLabel setHidden:NO];
        [_likeLabel setY:likeViewY];
        
        //计算collectionView的大小
        CGFloat height = ((int)(_prodArray.count+1)/2)*(YSProductListGridItemCellHeight+YSPublicXInset)+YSPublicXInset;
        [_collectView setFrame:CGRectMake(0, CGRectGetMaxY(_likeLabel.frame), SCREENW,height )];
        
        [_commentHeaderView setY:CGRectGetMaxY(_collectView.frame)];
        
        self.frame = CGRectMake(0, 0, SCREENW, CGRectGetMaxY(_commentHeaderView.frame));
    }
    
    if ([self.delegate respondsToSelector:@selector(webviewLoadFinish)]) {
        [_delegate webviewLoadFinish];
    }
}


#pragma Mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _prodArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    YSProductListGridItemCell *cell = [YSProductListGridItemCell cellWithCollectionView:collectionView indexPath:indexPath];
    [cell setProd:_prodArray[indexPath.row]];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat width = (SCREENW-3*YSPublicXInset)*0.5;
    return CGSizeMake(width, YSProductListGridItemCellHeight);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    YSProductList *itemInfo = _prodArray[indexPath.row];
    YSProductDetailCtrl *proddc = [[YSProductDetailCtrl alloc]initWithProdId:itemInfo.prodId];
    [self.superview.viewController.navigationController pushViewController:proddc animated:YES];
}

-(BOOL)haveData{
    return _havaData;
}

-(void)dealloc{
    // 移除观察者
    UIScrollView *scrollview = [[_webView subviews]firstObject];
    [scrollview removeObserver:self forKeyPath:@"contentSize"];
}

@end
